﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using OTS.Model;
using OTS.BLL;
using System.Text;
using System.Collections.Generic;

public partial class Admin_productAdd : OTS.AdminBasePage
{
    protected string strPid;
    protected void Page_Load(object sender, EventArgs e)
    {
        //测试时使用
        this.TestPurview(HttpContext.Current, OTS.enumSysRight.ProductManager);

        if (!Page.IsPostBack)
        {
            strPid = Request.QueryString["pId"];
            DoPageBind();
        }

    }
    private void DoPageBind()
    {

        if (Request.QueryString["pId"] == null)
        {
            Response.Redirect("productManager.aspx");
            return;
        }
        string _pId = Request.QueryString["pId"].ToString();
        this.txtID.Text = _pId;

        if (!OTS.Common.Help.IsNumber(_pId))
        {
            Response.Redirect("productManager.aspx");
            return;
        }
        int pId = int.Parse(_pId);

        OTS.Model.Product model = new OTS.Model.Product();
        OTS.BLL.ProductBLL bll = new OTS.BLL.ProductBLL();
        model = bll.GetSingleProduct(pId);
        if (model == null)
        {
            Response.Redirect("productManager.aspx");
            return;
        }
        //绑定品牌
        OTS.BLL.BrandBLL bllBrand = new OTS.BLL.BrandBLL();
        this.ddlBrand.DataSource = bllBrand.GetAllList();
        this.ddlBrand.DataBind();
        //绑定尺寸种类
        OTS.BLL.ProductSizeBLL bllSize = new OTS.BLL.ProductSizeBLL();
        this.ddlSizeMaterial.DataSource = bllSize.GetSizeMatList();
        this.ddlSizeMaterial.DataBind();
        string[] arrSizeIds = model.sizeIDs.Split(',');
        int sCount = arrSizeIds.Length;
        bool bSetOK = false;
        if (this.ddlSizeMaterial.Items.Count > 0)
        {
            if (model.sizeIDs.Length > 0)
            {
                string sId = "";
                for (int j = 0; j < sCount; j++)
                {
                    sId = arrSizeIds[j];

                    if (sId != "")
                    {
                        if (OTS.Common.Help.IsNumber(sId))
                        {
                            break;
                        }


                    }

                }

                string strMatId = bllSize.GetMatIdBySizeId(sId);
                if (strMatId != "")
                {
                    try
                    {
                        this.ddlSizeMaterial.SelectedValue = strMatId;
                        bSetOK = true;
                    }
                    catch
                    {
                        this.ddlSizeMaterial.SelectedIndex = 0;
                        bSetOK = false;
                    }
                }
            }

            BindSize();
            if (bSetOK) //赋值成功
            {

                for (int i = 0; i < sCount; i++)
                {
                    for (int j = 0; j < this.chkListSize.Items.Count; j++)
                    {
                        if (arrSizeIds[i] == this.chkListSize.Items[j].Value)
                        {
                            this.chkListSize.Items[j].Selected = true;
                        }
                    }
                }
            }

        }
        BindColorGroup();
        if (model.color != null && model.color != "")
        {
            string[] arrColorId = model.color.Split(',');
            for (int i = 0; i < this.cblColorGroup.Items.Count; i++)
            {
                for (int j = 0; j < arrColorId.Length; j++)
                {
                    if (this.cblColorGroup.Items[i].Value == arrColorId[j])
                    {
                        this.cblColorGroup.Items[i].Selected = true;
                    }
                }
            }
        }

        if (model.brandID > 0)
            this.ddlBrand.SelectedValue = model.brandID.ToString();

        this.ddlExpirySeason.SelectedValue = model.expirySeason.ToString();
        if (model.expiryYear > 0)
            this.ddlExpiryYear.SelectedValue = model.expiryYear.ToString();


        if (model.unit != null && model.unit != "")
            this.ddlUnit.SelectedValue = model.unit;
        this.txtCostPrice.Text = model.costPrice.ToString();
        this.txtEspecial.Text = model.especial.ToString();
        this.txtMaterial.Text = model.material.ToString();
        this.txtName.Text = model.proName.ToString();
        this.txtNO.Text = model.proNO.ToString();
        this.txtRetailPrice.Text = model.retailPrice.ToString();
        this.txtStyle.Text = model.style;
        //if(model.P_type != null)
        //    this.txtType.Text = model.P_type.typeName;
        //this.txtTypeID.Value = model.typeID.ToString();
        OTS.BLL.ProductTypeBLL bllType = new OTS.BLL.ProductTypeBLL();
        this.ddlType.DataSource = bllType.GetModelList(" parentID=1");
        this.ddlType.DataBind();
        try { this.ddlType.SelectedValue = model.typeID.ToString(); }
        catch { }
        this.ddlSex.SelectedValue = model.sex;
        //OTS.BLL.ProductTypeBLL pBll = new OTS.BLL.ProductTypeBLL();
        //OTS.Model.product_type mType = pBll.GetModel(model.typeID);

        //if (mType != null)
        //{
        //    this.txtTypeID.Value = mType.typeId.ToString();
        //    this.txtType.Text = mType.typeName;
        //}
        //else
        //{
        //    this.txtTypeID.Value = "0";
        //}

        this.txtWeight.Text = model.weight.ToString();
        this.txtTitle.Text = model.title;
        this.txtWholePrice.Text = model.wholeSalePrice.ToString();

        this.edit_content.Text = model.des;
        if (model.basicInformation_pic != "")
            this.imgBasic.ImageUrl = PictureProcessing.GetThumbURL(model.basicInformation_pic);
        else
            this.imgBasic.Visible = false;

        if (model.details_pic != "")
            this.imgDetail.ImageUrl = PictureProcessing.GetThumbURL(model.details_pic);
        else
            this.imgDetail.Visible = false;

        if (model.bigImg_pic != "")
            this.imgLft.ImageUrl = PictureProcessing.GetThumbURL(model.bigImg_pic);
        else
            this.imgLft.Visible = false;

        if (model.show_pic != "")
        {
            BindShowPic(model.show_pic);
        }
    }
    protected void BtnSave_Click(object sender, EventArgs e)
    {
        if (!OTS.Common.Help.IsNumber(this.txtID.Text))
        {
            return;
        }
        int pID = int.Parse(this.txtID.Text);
        ProductBLL proBLL = new ProductBLL();
        Product_Pic picModel = proBLL.GetPictures(pID);
        if (picModel == null)
            return;

        bool bCheckPic = true;
        //多图片上传
        HttpFileCollection files = HttpContext.Current.Request.Files;
        for (int i = 0; i < files.Count; i++)
        {
            if (files[i].FileName.Length > 0)
            {
                HttpPostedFile oFile = files[i];
                if (oFile.ContentLength / 1024 > 1024)  // 单个文件不能大于1M 
                {
                    OTS.Common.Jscript.Alert(System.IO.Path.GetFileName(oFile.FileName) + "---不能大于1M<br>");
                    bCheckPic = false;
                    break;
                }
                string fex = System.IO.Path.GetExtension(oFile.FileName);
                if (fex != ".jpg" && fex != ".JPG" && fex != ".jpeg" && fex != ".JPEG" && fex != ".gif" && fex != ".GIF" && fex != ".bmp" && fex != ".BMP")
                {
                    OTS.Common.Jscript.Alert(System.IO.Path.GetFileName(oFile.FileName) + "---图片格式不对，只能是jpg(JPG，jpeg，JPEG)、gif(GIF)和bmp(BMP)");
                    bCheckPic = false;
                    break;
                }
            }
        }
        if (!bCheckPic)
        {
            OTS.Common.Jscript.Alert("图片格式不正确！");
            return;
        }
        HttpPostedFile oLftShowFile = this.fuLftShowPic.PostedFile;
        HttpPostedFile oBasicInformationFile = this.fuBasicInformationPic.PostedFile;
        HttpPostedFile oDetailsFile = this.fuDetailsPic.PostedFile;

        Product pro = new Product();

        //返回文件的扩展名

        string leftPic = PictureProcessing.SaveFilePic(oLftShowFile, this.txtID.Text + "_" + OTS.Common.Help.GetUniqueKey());    //上传左侧显示图片
        string basicInformationPic = PictureProcessing.SaveFilePic(oBasicInformationFile, this.txtID.Text + "_" + OTS.Common.Help.GetUniqueKey()); //上传基本信息图片
        string detailsPic = PictureProcessing.SaveFilePic(oDetailsFile, this.txtID.Text + "_" + OTS.Common.Help.GetUniqueKey());   //上传细节展示图片

        //pro.color;
        //如果本次上传了，就把原来的图片删除
        //否则就保持原来的图片 
        string strSrcPath;
        if (leftPic != "")
        {
            pro.bigImg_pic = leftPic;

            PictureProcessing.SaveProductFileThumPic(leftPic, PictureProcessing.GetThumbPath(leftPic));
            if (picModel.bigImg_pic != "")
            {
                strSrcPath = System.Web.HttpContext.Current.Server.MapPath(picModel.bigImg_pic);
                try
                {
                    System.IO.File.Delete(strSrcPath);
                }
                catch { }
                try
                { System.IO.File.Delete(PictureProcessing.GetThumbPath(picModel.bigImg_pic)); }
                catch { }
            }

            this.imgLft.ImageUrl = leftPic;
            this.imgLft.Visible = true;

        }
        else
        {
            pro.bigImg_pic = picModel.bigImg_pic;
        }


        if (basicInformationPic != "")
        {
            pro.basicInformation_pic = basicInformationPic;
            PictureProcessing.SaveProductFileThumPic(basicInformationPic, PictureProcessing.GetThumbPath(basicInformationPic));
            if (picModel.basicInformation_pic != "")
            {
                strSrcPath = System.Web.HttpContext.Current.Server.MapPath(picModel.basicInformation_pic);
                try
                {
                    System.IO.File.Delete(strSrcPath);
                }
                catch { }
                try
                { System.IO.File.Delete(PictureProcessing.GetThumbPath(picModel.basicInformation_pic)); }
                catch { }
            }
            this.imgBasic.ImageUrl = basicInformationPic;
            this.imgBasic.Visible = true;

        }
        else
        {
            pro.basicInformation_pic = picModel.basicInformation_pic;
        }

        if (detailsPic != "")
        {
            pro.details_pic = detailsPic;
            PictureProcessing.SaveProductFileThumPic(detailsPic, PictureProcessing.GetThumbPath(detailsPic));
            if (picModel.details_pic != "")
            {
                strSrcPath = System.Web.HttpContext.Current.Server.MapPath(picModel.details_pic);
                try
                {
                    System.IO.File.Delete(strSrcPath);
                }
                catch { }
                try
                { System.IO.File.Delete(PictureProcessing.GetThumbPath(picModel.details_pic)); }
                catch { }
            }
            this.imgDetail.ImageUrl = detailsPic;
            this.imgDetail.Visible = true;
        }
        else
        {
            pro.details_pic = picModel.details_pic;
        }



        for (int i = 3; i < files.Count; i++)
        {
            HttpPostedFile myFile = files[i];
            string strFileName = PictureProcessing.SaveFilePic(myFile, this.txtID.Text + "_" + OTS.Common.Help.GetUniqueKey());   //上传细节展示图片 

            if (strFileName != "")
            {
                PictureProcessing.SaveProductFileThumPic(strFileName, PictureProcessing.GetThumbPath(strFileName));
                picModel.show_pic.Add(strFileName);
            }
        }
        BindShowPic(picModel.show_pic);

        StringBuilder buildShowPic = new StringBuilder();
        string strShowPic = "";
        for (int i = 0; i < picModel.show_pic.Count; i++)
        {
            buildShowPic.Append(picModel.show_pic[i] + ",");
        }
        strShowPic = buildShowPic.ToString();
        if (strShowPic != "")
        {
            strShowPic = strShowPic.Substring(0, strShowPic.Length - 1);
        }
        pro.show_pic = strShowPic;

        pro.proID = Int32.Parse(this.txtID.Text);
        pro.proNO = this.txtNO.Text;
        pro.proName = this.txtName.Text;
        pro.brandID = Int32.Parse(this.ddlBrand.SelectedValue);
        pro.typeID = Int32.Parse(this.ddlType.SelectedValue);
        pro.sex = this.ddlSex.SelectedValue;
        pro.style = this.txtStyle.Text;
        pro.costPrice = double.Parse(this.txtCostPrice.Text);
        pro.wholeSalePrice = double.Parse(this.txtWholePrice.Text);
        pro.retailPrice = double.Parse(this.txtRetailPrice.Text);
        pro.unit = this.ddlUnit.SelectedValue.ToString();
        pro.weight = double.Parse(this.txtWeight.Text);
        pro.material = this.txtMaterial.Text;
        pro.especial = this.txtEspecial.Text;
        pro.expiryYear = Int32.Parse(this.ddlExpiryYear.SelectedValue);
        pro.expirySeason = Int32.Parse(this.ddlExpirySeason.SelectedValue);
        pro.title = this.txtTitle.Text;
        string strColorIds = "";
        for (int i = 0; i < this.cblColorGroup.Items.Count; i++)
        {
            if (this.cblColorGroup.Items[i].Selected)
            {
                strColorIds += this.cblColorGroup.Items[i].Value + ",";
            }
        }
        if (strColorIds != "")
        {
            strColorIds = strColorIds.Substring(0, strColorIds.Length - 1);
        }
        pro.color = strColorIds;


        string size = "";

        if (chkListSize.SelectedIndex == -1)
        {
            OTS.Common.Jscript.Alert("请选择至少一个码数！");
            return;
        }
        else
        {
            foreach (ListItem li in this.chkListSize.Items)
            {
                if (li.Selected)
                {
                    size += li.Value.ToString() + ",";
                }
            }
            size = size.Substring(0, size.Length - 1);
            pro.sizeIDs = size;
        }
        pro.des = this.edit_content.Text;

        if (this.txtID.Text == "0" || this.txtID.Text == "")    //增加
        {

        }
        else
        {
            pro.proID = Int32.Parse(this.txtID.Text);
            if (proBLL.Update(pro))
            {
                OTS.Common.Jscript.Alert("修改成功！");
                return;
            }
            else
            {
                OTS.Common.Jscript.Alert("修改失败！");
                return;
            }
        }
    }


    protected void ddlSizeMaterial_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindSize();
    }
    private void BindSize()
    {
        int matId = 0;
        if (this.ddlSizeMaterial.SelectedValue != null)
            matId = int.Parse(this.ddlSizeMaterial.SelectedValue);
        if (matId > 0)
        {
            OTS.BLL.ProductSizeBLL bll = new OTS.BLL.ProductSizeBLL();
            this.chkListSize.DataSource = bll.GetSizeList(matId);
            this.chkListSize.DataBind();
            this.upSize.Update();
        }

    }
    private void BindColorGroup()
    {
        OTS.BLL.ColorBLL bll = new ColorBLL();
        this.cblColorGroup.DataSource = bll.GetAllList();
        this.cblColorGroup.DataBind();
    }
    private void BindShowPic(List<string> list)
    {
        string strFilePaths = "";
        for (int i = 0; i < list.Count; i++)
        {
            strFilePaths += list[i] + ",";
        }
        if (strFilePaths.Length > 0)
        {
            strFilePaths = strFilePaths.Substring(0, strFilePaths.Length - 1);
            BindShowPic(strFilePaths);
        }

    }
    private void BindShowPic(string urls)
    {
        string[] arrPath = urls.Split(',');
        DataTable dt = new DataTable();
        dt.Columns.Add("imgURL", typeof(string));
        dt.Columns.Add("fileName", typeof(string));
        for (int i = 0; i < arrPath.Length; i++)
        {
            DataRow dr = dt.NewRow();
            dr["imgURL"] = PictureProcessing.GetThumbURL(arrPath[i]);
            dr["fileName"] = System.IO.Path.GetFileNameWithoutExtension(Server.MapPath(arrPath[i]));
            dt.Rows.Add(dr);
        }
        this.rptShowPic.DataSource = dt;
        this.rptShowPic.DataBind();
    }
}
